package com.atguigu.msmservice.cotroller;


import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Auther 赵乾坤
 * @Date 2020-11-30 15:25
 */
@Api(description="短信管理")
@RestController
@RequestMapping("/edumsm/phone")
@CrossOrigin
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @ApiOperation(value = "根据手机号发送验证码短信")
    @GetMapping("sendMsmPhone/{phone}")
    public R sendMsmPhone(@PathVariable String phone) {
        //1.从reids里获取验证码
        String rPhone = redisTemplate.opsForValue().get(phone);
        //2.如果有验证码，返回页面
        if (rPhone != null) {
            return R.ok();
        }
        //3.如果没有，生成验证码
        String code = RandomUtil.getFourBitRandom();
        //4.调用service方法发送短信
        Map<String, Object> param = new HashMap<>();
        param.put("code",code);
        boolean isSend = msmService.sendMsmPhone(phone,param);
        //5.发送成功后，验证码存入redis，5分钟有效
        if (isSend) {
            //手机短信过期时间设置 为 5 分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        }



        return R.ok();
    }

}
